package com.hfkh.keyun.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hfkh.keyun.common.ApiResult;
import com.hfkh.keyun.entity.Resource;
import com.hfkh.keyun.exception.BusinessException;
import com.hfkh.keyun.mapper.ResourceMapper;
import com.hfkh.keyun.service.ResourceService;
import com.hfkh.keyun.vo.ResourceVO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService{

    @Autowired
    private ResourceMapper resourceMapper;
    @Override
    public Page<Resource> selectResourcePage(Page<Resource> page, Integer majorId) {
        // 实例化一个查询条件构造器
        QueryWrapper<Resource> queryWrapper = new QueryWrapper();
        Page<Resource> resourcePage = resourceMapper.selectPage(page, queryWrapper);
        return resourcePage;
    }

    @Override
    public ApiResult AddSumUpdResource(ResourceVO resourceVO) throws IOException,BusinessException{

        MultipartFile file = resourceVO.getFile();
        //注意参数
        if (file.isEmpty()) {
            return ApiResult.fail("文件为空！");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        String newFileName = UUID.randomUUID()+suffixName;

        String filePathSql = "http://localhost:8080/images/";
        String filePath = "D:/spring/demo/keyun/src/main/resources/static/images/";
        String path = filePath + newFileName;
        String pathSql = filePathSql + newFileName;
        File dest = new File(new File(path).getAbsolutePath());// dist为文件，有多级目录的文件
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            //因此这里使用.getParentFile()，目的就是取文件前面目录的路径
            dest.getParentFile().mkdirs();// 新建文件夹
        }
        file.transferTo(dest);//文件写入

        Resource rs = new Resource();
        rs.setId(resourceVO.getId());
        rs.setResourceTitle(resourceVO.getResourceTitle());
        rs.setResourceUrl(resourceVO.getResourceUrl());
        rs.setPicUrl(pathSql);
        rs.setMajorId(resourceVO.getMajorId());
        if(resourceVO.getId()==null){
            resourceMapper.insert(rs);
            return ApiResult.fail("新增成功！");
        }
        resourceMapper.updateById(rs);
        return ApiResult.fail("修改成功！");
    }
}
